# coding=utf-8
from flask import Blueprint,request,jsonify,make_response,redirect,g
import json
from common.models.User import User # 引入数据库查询ORM
from common.libs.UserService.UserService import UserService # 引入账号密码验证
from application import app,db
from common.libs.UrlManager import UrlManager
from common.libs.Helper import ops_render

route_user = Blueprint( 'user_page',__name__ )


# 登录
# GET请求渲染页面，POST请求登录
@route_user.route( "/login", methods=["GET", "POST"] )
def login():
    # 如果是GET请求，则展示登录页面
    if (request.method == "GET"):
        return ops_render( "user/login.html" )

    # 如果是POST请求，则为提交
    else:
        # 返回的变量
        resp = {
            'code': 200, # 200为正常，-1为出错
            'msg': '登录成功',
            'data': {}
        }

        req = request.values # 获取请求的参数（dict类型）,key值为表单 input 的 name 值

        login_name = req['login_name'] if 'login_name' in req else '' # 判断 login_name 是否在请求的参数中
        login_pwd = req['login_pwd'] if 'login_pwd' in req else ''  # 判断 login_pwd 是否在请求的参数中

        # 输入的用户名不符合规范
        if login_name is None or len(login_name)<1:
            resp['code'] = -1
            resp['msg'] = '登录失败，请输入正确的登录用户名'
            return jsonify(resp)

        # 输入的密码不符合规范
        if login_pwd is None or len(login_pwd)<1:
            resp['code'] = -1
            resp['msg'] = '登录失败，请输入正确的登录密码'
            return jsonify(resp)

        # 查询用户是否存在
        user_info = User.query.filter_by(login_name = login_name).first()
        if not user_info:
            resp['code'] = -1
            resp['msg'] = '该用户不存在'
            return jsonify(resp)

        # 验证登录名和密码
        if user_info.login_pwd != UserService.genePwd(login_pwd, user_info.login_salt):
            resp['code'] = -1
            resp['msg'] = '请输入正确的用户名和密码'
            return jsonify(resp)

        # 用户已被删除（状态不对）
        if user_info.status != 1:
            resp['code'] = -1
            resp['msg'] = '账号已被禁用'
            return jsonify(resp)

        # 设置cookie
        response = make_response(json.dumps(resp))
        response.set_cookie(app.config['AUTH_COOKIE_NAME'], "%s#%s"%(UserService.geneAuthCode(user_info), user_info.uid))

        # 登录成功
        return response


@route_user.route( "/edit", methods=["GET", "POST"] )
def edit():
    # 如果是GET请求，则展示登录页面
    if request.method == "GET":
        return ops_render( "user/edit.html", { 'current': 'edit' } )
    # 如果是POST请求，则为提交
    else:
        # 返回的变量
        resp = {
            'code': 200,  # 200为正常，-1为出错
            'msg': '修改成功',
            'data': {}
        }

        req = request.values  # 获取请求的参数（dict类型）,key值为表单 input 的 name 值

        nickname = req['nickname'] if 'nickname' in req else ''
        email = req['email'] if 'email' in req else ''

        if nickname is None or len(nickname)<1:
            resp['code'] = -1
            resp['msg'] = '请输入符合规范的姓名'
            return jsonify(resp)

        if email is None or len(email)<1:
            resp['code'] = -1
            resp['msg'] = '请输入符合规范的邮箱'
            return jsonify(resp)

        user_info = g.current_user
        user_info.nickname = nickname
        user_info.email = email

        db.session.add(user_info)
        db.session.commit()

        # 设置cookie
        response = make_response(json.dumps(resp))
        response.set_cookie(app.config['AUTH_COOKIE_NAME'], "%s#%s" % (UserService.geneAuthCode(user_info), user_info.uid))

        return response


# 用户修改密码
@route_user.route( "/reset-pwd", methods=["GET", "POST"] )
def resetPwd():
    # 如果是GET请求，则展示登录页面
    if request.method == "GET":
        return ops_render( "user/reset_pwd.html", { 'current': 'reset-pwd' } )
    # 如果是POST请求，则为提交
    else:
        # 返回的变量
        resp = {
            'code': 200,  # 200为正常，-1为出错
            'msg': '修改成功',
            'data': {}
        }

        req = request.values  # 获取请求的参数（dict类型）,key值为表单 input 的 name 值

        old_password = req['old_password'] if 'old_password' in req else ''
        new_password = req['new_password'] if 'new_password' in req else ''

        if old_password is None or len(old_password) < 6:
            resp['code'] = -1
            resp['msg'] = '请输入符合规范的旧密码'
            return jsonify(resp)

        if new_password is None or len(new_password) < 6:
            resp['code'] = -1
            resp['msg'] = '请输入符合规范的新密码'
            return jsonify(resp)

        if old_password == new_password:
            resp['code'] = -1
            resp['msg'] = '新旧密码不可一致'
            return jsonify(resp)

        user_info = g.current_user
        user_info.login_pwd = UserService.genePwd(new_password, user_info.login_salt)

        db.session.add(user_info)
        db.session.commit()



        return jsonify(resp)


# 用户登出
# 清理cookie，并跳转到登录页面
@route_user.route( "/logout" )
def logout():
    response = make_response(redirect(UrlManager.buildUrl('/user/login')))
    response.delete_cookie(app.config['AUTH_COOKIE_NAME'])
    return response
